<template>
  <div class="purse">
    <div class="purse-header">
      <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item :to="{ path: '/mechanism/home/menu' }"
          >首页</el-breadcrumb-item
        >
        <el-breadcrumb-item>我的钱包</el-breadcrumb-item>
      </el-breadcrumb>
    </div>
    <div class="purse-main clearfloat">
      <div class="main_left fl">
        <!--  v-if="$store.state.user.vip" -->
        <div class="user_info">
          <el-upload
            class="upload-demo"
            :action="uploadImgUrl"
            :on-success="handleSuccess"
            :on-error="handleError"
            :show-file-list="false"
            multiple
            :before-upload="beforeUpload"
          >
            <img
              :src="baseUrl + '/storage/upload/' + $store.state.user.img"
              class="avatar"
            />
          </el-upload>
          <!-- <el-popover
            placement="bottom"
            trigger="click"
            width="120"
            >
            <el-upload
              class="upload-demo"
              :action="uploadImgUrl"
              :on-success="handleSuccess"
              :show-file-list="false"
              multiple
              :limit="1"
              :before-upload="beforeUpload">
              <el-button size="small" type="primary" style="margin-left:22px">更换图像</el-button>
            </el-upload>
            <el-avatar slot="reference" :size="70" :src="baseUrl + '/storage/upload/' + $store.state.user.img" fit='contain'></el-avatar>
          </el-popover>-->
          <template v-if="$store.state.user.vip">
            <template v-if="$store.state.user.vip">
              <div class="info-vip" @click="tovipPage">
                <el-popover
                  placement="right"
                  title="当前会员等级权益"
                  width="300"
                  trigger="hover"
                  v-if="$store.state.user.vip != 0"
                >
                  <div class="vip_Introduction">
                    <ul>
                      <li>
                        <span>1，案件即时结算。</span>
                      </li>
                      <li>
                        <span>2，推荐新代理人完成案件，可获得奖励。</span>
                      </li>
                      <li>
                        <span>3，具有代理人评级资格。</span>
                        <br />
                      </li>
                      <li>
                        <span>4，余额可提现至非本人账号。</span>
                        <br />
                      </li>
                      <li>
                        <span>5，代理人收益免收税费。</span>
                        <br />
                      </li>
                      <li>
                        <span v-if="$store.state.user.grade > 2">
                          6，每月最低完成案件数为
                          <font class="font_success">0</font>件。
                        </span>
                        <span v-if="3 > $store.state.user.grade > 0">
                          6，每月最低完成案件数为
                          <font class="font_success">2</font>件。
                        </span>
                        <br />
                      </li>
                      <li>
                        <span v-if="$store.state.user.grade > 1">
                          7，可带徒弟，徒弟案件结算费用的
                          <font class="font_success">50%</font>作为指导费。
                        </span>
                        <br />
                      </li>
                      <li>
                        <span v-if="$store.state.user.grade == 3">
                          8，代理人可进行
                          <font class="font_success">1</font>次无理由申诉。
                        </span>
                        <br />
                      </li>
                    </ul>
                  </div>
                  <i slot="reference" class="el-icon-info orange ml10"></i>
                </el-popover>
              </div>
            </template>
            <div class="expire">
              <!-- <span>到期时间：</span>
              <span>{{ $store.state.user.vip_expire_time | formatTime}}</span>-->
            </div>
            <!-- <el-button class="renewal" @click="renewal">续费</el-button> -->
          </template>
          <!-- <div v-else>
            <el-button type="primary" class="upgradeVIP" @click="renewal">升级VIP</el-button>
          </div>-->
          <div class="money">
            <div class="frozenCoin clearfloat">
              <span class="label">冻结金额：</span>
              <span>{{ frozenCoin }}元</span>
              <el-popover
                placement="right"
                title="冻结金额说明"
                width="300"
                trigger="hover"
              >
                <span>
                  冻结金额为近
                  <font class="font_success">20</font>天的结算金额，每笔结算金额
                  <font class="font_success">20</font>天后自动解冻为可提现金额。
                </span>
                <i slot="reference" class="el-icon-info orange fr"></i>
              </el-popover>
            </div>
            <div class="coin clearfloat">
              <span class="label">我的余额：</span>
              <span>{{ coin }}元</span>
              <el-button class="cashing-btn fr" @click="cashing"
                >提现</el-button
              >
            </div>
          </div>
        </div>
        <div class="bg" v-if="$store.state.user.vip"></div>
      </div>
      <div class="main_right fr">
        <div class="herder clearfloat">
          <span class="title fl">我的余额明细</span>
          <div class="fr btns">
            <el-select
              v-model="detailTypes"
              multiple
              collapse-tags
              @change="queryTypes"
              placeholder="选择明细类型查询"
            >
              <el-option
                v-for="item in detailTypeOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
            <!-- <el-date-picker
              v-model="createdTime"
              unlink-panels
              type="daterange"
              range-separator="至"
              format='yyyy-MM-dd'
              value-format='yyyy-MM-dd'
              start-placeholder="开始日期"
              @change='confirmQuery'
            end-placeholder="结束日期">-->

            <!-- </el-date-picker> -->
            <el-date-picker
              v-show="isDetailsTime"
              v-model="createdTime"
              unlink-panels
              type="daterange"
              range-separator="至"
              format="yyyy-MM-dd"
              value-format="yyyy-MM-dd"
              start-placeholder="开始日期"
              @change="confirmQuery"
              end-placeholder="结束日期"
              :picker-options="detailsPickerOptions"
            ></el-date-picker>
            <el-date-picker
              v-show="!isDetailsTime"
              v-model="createdTimeMonth"
              type="month"
              @change="confirmQueryMonth"
              value-format="yyyy-MM-dd"
              placeholder="选择月"
              :picker-options="monthPickerOptions"
            ></el-date-picker>
            <el-button
              @click="isDetailsTime = !isDetailsTime"
              type="primary"
              :icon="isDetailsTime ? 'el-icon-arrow-left' : 'el-icon-more'"
            ></el-button>
          </div>
        </div>
        <!-- 
          v-infinite-scroll="load"
          infinite-scroll-disabled="disabled"
          infinite-scroll-delay='1000'
          infinite-scroll-distance='40'
          infinite-scroll-immediate='false'
        -->
        <el-table
          v-show="showTable"
          :data="detailData"
          ref="table"
          stripe
          border
          style="width: 100%"
          height="100%"
        >
          <el-table-column
            prop="number"
            label="编号"
            :show-overflow-tooltip="true"
          >
            <!-- <template slot-scope="scope">
              {{ scope.row | payMethod }}
            </template>-->
          </el-table-column>
          <el-table-column prop="type" label="明细类型">
            <template slot-scope="scope">{{
              scope.row.type | agentPurseType
            }}</template>
          </el-table-column>
          <el-table-column prop="money" label="金额">
            <template slot-scope="scope">
              <span
                :class="scope.row.money >= 0 ? 'font_success' : 'font_danger'"
                >{{
                  scope.row.money > 0 ? `+${scope.row.money}` : scope.row.money
                }}</span
              >
            </template>
          </el-table-column>
          <el-table-column
            prop="created_at"
            label="时间"
            :show-overflow-tooltip="true"
          >
            <template slot-scope="scope">{{ scope.row.created_at }}</template>
          </el-table-column>
          <el-table-column
            fixed="right"
            label="操作"
            width="100"
            align="center"
          >
            <template slot-scope="scope">
              <el-button
                v-if="scope.row.type == 0"
                size="small"
                type="primary"
                :disabled="
                  scope.row.drawing && scope.row.drawing.agency_drawing_invoice_record ? true : false
                "
                @click="uploadInvoice(scope.row)"
                >上传发票</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
    <withdrawDialog ref="withdrawDialog" @refresh="refresh"></withdrawDialog>
    <uploadInvoice ref="uploadInvoice" @refresh="refresh" />
  </div>
</template>

<script>
import { getUserInfo, updateUser, getMyInfo } from "~/api/user";
import moment from "moment";
import withdrawDialog from "./components/withdrawDialog";
import uploadInvoice from "./components/uploadInvoice";
import { detailTypeOptions } from "./components/config";
import { apiAddress } from "~/util/config.js";
export default {
  components: {
    withdrawDialog,
    uploadInvoice,
  },
  data() {
    return {
      tx_img: "",
      uploadImgUrl: global.baseurl + "/api/upload/img",
      frozenCoin: 0,
      coin: 0,
      detailTypes: "",
      detailTypeOptions: detailTypeOptions,
      createdTime: [],
      createdTimeMonth: "",
      detailData: [],
      paramsByPurse: {
        is_frozee: 0,
        type: "0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,20",
      },
      showTable: true,
      noMore: false,
      dom: null,
      page: 1,
      baseUrl: global.baseurl,
      isDetailsTime: false,
      withdrawal_record: [],
      drawalList: [],
      monthPickerOptions: {
        shortcuts: [
          {
            text: "重置",
            onClick(picker) {
              picker.$emit("pick", "");
            },
          },
        ],
      },
      detailsPickerOptions: {
        shortcuts: [
          {
            text: "重置",
            onClick(picker) {
              picker.$emit("pick", "");
            },
          },
          {
            text: "近三个月",
            onClick(picker) {
              let end = new Date();
              let now = new Date();
              const start = new Date(now.setMonth(now.getMonth() - 3));
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "近六个月",
            onClick(picker) {
              let end = new Date();
              let now = new Date();
              const start = new Date(now.setMonth(now.getMonth() - 6));
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "近一年",
            onClick(picker) {
              let end = new Date();
              let now = new Date();
              const start = new Date(now.setMonth(now.getMonth() - 12));
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "近两年",
            onClick(picker) {
              let end = new Date();
              let now = new Date();
              const start = new Date(now.setMonth(now.getMonth() - 24));
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "近三年",
            onClick(picker) {
              let end = new Date();
              let now = new Date();
              const start = new Date(now.setMonth(now.getMonth() - 36));
              picker.$emit("pick", [start, end]);
            },
          },
        ],
      },
    };
  },
  computed: {
    disabled() {
      return this.noMore;
    },
  },
  mounted() {
    // 获取需要绑定的table
    this.dom = this.$refs.table.bodyWrapper;
    this.dom.addEventListener("scroll", () => {
      // 滚动距离
      let scrollTop = this.dom.scrollTop;
      // 变量windowHeight是可视区的高度
      let windowHeight = this.dom.clientHeight || this.dom.clientHeight;
      // 变量scrollHeight是滚动条的总高度
      let scrollHeight = this.dom.scrollHeight || this.dom.scrollHeight;
      if (scrollTop + windowHeight === scrollHeight) {
        // 获取到的不是全部数据 当滚动到底部 继续获取新的数据

        if (!this.noMore) {
          this.load();
        }
      }
    });
  },
  created() {
    // 默认查询当月明细
    let nowTiem = {
      start_time: `${moment().format("YYYY-MM")}-01`,
      end_time: `${moment().format("YYYY-MM")}-31`,
    };
    // this.paramsByPurse.start_time = `${moment().format("YYYY-MM")}-01`
    // this.paramsByPurse.end_time = `${moment().format("YYYY-MM")}-31`
    (this.baseUrl = apiAddress),
      (this.uploadImgUrl = apiAddress + "/api/upload/img"),
      (this.createdTime[0] = nowTiem.start_time);
    this.createdTime[1] = nowTiem.end_time;
    this.paramsByPurse.start_time = this.createdTime[0];
    this.paramsByPurse.end_time = this.createdTime[1];
    // this.getDetailsData(this.paramsByPurse);
    this.getDetailsData();
    this.queryBalance();
    // this.getVipLogo()
    this.getDrawal();
  },
  methods: {
    // 获取个人成就信息
    getUser() {
      this.$axios
        .get("/api/consumer/show")
        .then((res) => {
          if (res.data.code == 200) {
            this.$store.commit("setUser", res.data.data);
          }
        })
        .catch((err) => {
          this.$message.error(err);
        });
    },
    handleError(res, file, fileList) {},
    handleSuccess(res, file, fileList) {
      if (res.code == 200) {
        this.tx_img = res.data;
        let obj = {};
        obj.tx_img = this.tx_img;
        updateUser(this.$axios, obj)
          .then((res) => {
            if (res.data.code == 200) {
              this.$alert("头像修改成功！", "提示", {
                confirmButtonText: "确定",
                type: "success",
                center: true,
                callback: (action) => {
                  // this.getUser();
                  let obj1 = this.$store.state.user;
                  obj1.img = obj.tx_img;
                  this.$store.commit("setUser", obj1);
                },
              });
            } else {
              this.$message({
                message: res.data.message,
                type: "error",
              });
            }
          })
          .catch((err) => {
            this.$message({
              message: err,
              type: "error",
            });
          });
      } else {
        this.$alert(res.message, "提示", {
          confirmButtonText: "确定",
          callback: (action) => {},
        });
      }
    },
    beforeUpload(file) {
      let that = this;
      let canUpload = true; //是否能够上传（布尔值）
      let type = file.name.substring(file.name.lastIndexOf(".") + 1);
      //不区分大小写
      if (!/jpg|jpeg|png|gif|ico/i.test(type)) {
        that.$message({
          message: "文件格式只能是jpg/jpeg/png/gif/ico",
          type: "warning",
        });
        canUpload = false;
      }
      let size = file.size / 1024 / 1024;
      if (size > 0.3) {
        that.$message({
          message: "文件大小不能超过300kb",
          type: "warning",
        });
        canUpload = false;
      }
      return canUpload;
    },
    tovipPage() {
      this.$router.push("/mechanism/vip");
    },
    renewal() {
      // 购买vip
      this.$router.replace({
        name: "payment",
        query: {
          type: "buyVip",
          vip: btoa("vip1"),
          from: this.$route.path,
        },
      });
    },
    getDrawal() {
      this.$axios.get("api/withdrawal").then((res) => {
        if (res.data.code == 200) {
          this.drawalList = res.data.data;
        } else {
          this.$alert(res.data.message, "提示", {
            confirmButtonText: "确定",
            center: true,
            type: "warning",
            callback: (action) => {},
          });
        }
      });
    },
    cashing() {
      if (this.drawalList.length > 0) {
        if (this.coin > 0) {
          this.queryBalance();
          let data = {
            coin: this.coin,
            frozenCoin: this.frozenCoin,
          };
          this.$refs.withdrawDialog.show(data);
        } else if (this.coin <= 0 && this.$store.state.user.vip > 0) {
          this.$alert(`<p>您的账户余额不足，暂无法提现！</p>`, "提示", {
            confirmButtonText: "确定",
            center: true,
            dangerouslyUseHTMLString: true,
            callback: (action) => {},
          });
        }

        // else if (this.$store.state.user.vip == 0) {
        //   this.$alert(`<p>您目前身份不是vip，暂无法提现！</p>`, "提示", {
        //     confirmButtonText: "确定",
        //     center: true,
        //     dangerouslyUseHTMLString: true,
        //     callback: action => {}
        //   });
        // }
      } else {
        this.$alert(`<p>您还没有默认收款人信息，请去添加后提现！</p>`, "提示", {
          confirmButtonText: "去添加",
          center: true,
          dangerouslyUseHTMLString: true,
          callback: (action) => {
            if (action != "cancel") {
              this.$router.push("/agent/home/bankCard");
            }
          },
        });
      }
    },
    confirmQuery() {
      if (this.createdTime) {
        this.paramsByPurse.start_time = this.createdTime[0];
        this.paramsByPurse.end_time = this.createdTime[1];
        this.getDetailsData(this.paramsByPurse);
      } else {
        this.getDetailsData();
      }
    },
    confirmQueryMonth() {
      if (this.createdTimeMonth) {
        let value = this.createdTimeMonth.split("-");
        (this.paramsByPurse.start_time = `${value[0]}-${value[1]}-${value[2]} 00:00:00`),
          (this.paramsByPurse.end_time = `${value[0]}-${value[1]}-31 00:00:00`);
        this.getDetailsData(this.paramsByPurse);
      } else {
        this.getDetailsData();
      }
    },

    queryTypes(value) {
      if (value) {
        this.paramsByPurse.type = value.join(",");
      } else {
        this.paramsByPurse.type =
          "0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,20";
      }
      this.getDetailsData(this.paramsByPurse);
    },
    // 获取明细数据
    getDetailsData(pParams, scrollData) {
      let params = {};
      params = { ...params, ...this.paramsByPurse };
      if (pParams) {
        params = { ...params, ...pParams, ...this.paramsByPurse };
      }

      this.$axios
        .get("api/drawing/wallet/agent_detail", {
          params: params,
        })
        .then((res) => {
          if (res.data.code == 200) {
            if (scrollData) {
              let data = res.data.data;
              if (data.length == 0) {
                this.noMore = true;
              }
              this.detailData = this.detailData.concat(data);
            } else {
              this.detailData = res.data.data;
              this.dom.scrollTop = this.dom.scrollTop - 100;
            }
          } else {
            this.$message.error(res.data.message);
          }
        });
    },
    // 获取余额
    queryBalance() {
      this.$axios.get("api/drawing/wallet").then((res) => {
        if (res.data.code == 200) {
          this.coin = res.data.data.coin;
          this.frozenCoin = res.data.data.frozenCoin;
        } else if (res.data.code == 400) {
          this.$message.error(res.data.message);
        }
      });
    },
    refresh() {
      let nowTiem = {
        start_time: `${moment().format("YYYY-MM")}-01`,
        end_time: `${moment().format("YYYY-MM")}-31`,
      };
      this.getDetailsData(nowTiem);
      this.queryBalance();
    },
    load() {
      this.page++;
      this.paramsByPurse.page = this.page;
      this.getDetailsData(this.paramsByPurse, true);
    },
    // 上传发票
    uploadInvoice(data) {
      this.$refs["uploadInvoice"].show(data);
    },
  },
};
</script>

<style lang='less'>
.purse {
  width: 90%;
  height: 100%;
  min-height: 450px;
  padding: 30px;
  margin: 0 auto;
  box-sizing: border-box;
  background: rgba(255, 255, 255, 1);
  &-header {
    height: 45px;
    .el-breadcrumb {
      .el-breadcrumb__item {
        .el-breadcrumb__inner,
        .el-breadcrumb__separator {
          font-size: 25px;
          color: rgba(0, 35, 151, 1);
          font-weight: 400;
        }
      }
      .el-breadcrumb__item:first-child {
        .el-breadcrumb__inner {
          padding-left: 10px;
          border-left: 5px solid #002397;
        }
      }
    }
    border-bottom: 2px solid #e5e5e5;
    box-sizing: border-box;
  }

  &-main {
    margin-top: 30px;
    width: 100%;
    box-sizing: border-box;
    height: calc(100% - 75px);
    .main_left {
      width: 300px;
      height: 100%;
      background: linear-gradient(
        0deg,
        rgba(117, 185, 255, 1) 0%,
        rgba(22, 137, 255, 1) 100%
      );

      .user_info {
        height: 330px;
        box-sizing: border-box;
        padding-top: 40px;
        // .el-avatar {
        //   margin: 0 auto;
        //   display: block;
        // }
        .upload-demo {
          // align-items: center;
          display: flex;
          justify-content: center;
        }
        .avatar {
          margin: 0 auto;
          display: block;
          width: 70px;
          height: 70px;
          border-radius: 50%;
          // display: block;
        }

        .info-vip {
          height: 28px;
          width: 29px;
          margin: 17px auto 0;
          background: url("../../../assets/img/图标.png") no-repeat;
          background-position: -97px -100px;
          position: relative;
          .el-icon-info {
            position: absolute;
            right: -20px;
            top: 8px;
          }
        }
        .expire {
          font-size: 12px;
          color: rgba(255, 255, 255, 1);
          margin: 12px auto 0;
          width: 100%;
          text-align: center;
        }
        .upgradeVIP {
          padding: 7px 24px 7px 23px;
          background: #0090ff;
          display: block;
          margin: 17px auto 0;
          border-radius: 0px;
        }
        .renewal {
          font-size: 12px;
          padding: 4px 18px;
          background: #ffa200;
          border-radius: 10px;
          margin: 11px auto 0;
          display: block;
          border-color: #ffa200;
          color: #fff;
        }
        .money {
          height: 90px;
          width: 270px;
          margin: 20px auto 0;
          padding: 20px 8px 0px 8px;
          border-top: 1px solid rgba(255, 255, 255, 1);
          box-sizing: border-box;

          .frozenCoin {
            font-size: 15px;
            color: #fc8200;
          }
          .coin {
            font-size: 17px;
            color: #002d88;
            line-height: 17px;
            margin-top: 5px;

            .cashing-btn {
              font-size: 12px;
              padding: 3px 18px;
              background: #2368b0;
              border-radius: 10px;
              border-color: #2368b0;
              color: #fff;
            }
          }
          .label {
            color: #fff;
          }
        }
      }
      .bg {
        height: calc(100% - 330px);
        background: url("../../../assets/img/V.png") no-repeat;
      }
    }

    .main_right {
      width: calc(100% - 300px);
      height: 100%;
      padding: 0 0 0 27px;
      display: flex;
      flex-direction: column;

      .herder {
        min-height: 60px;
        width: 100%;

        .title {
          display: inline-block;
          padding-top: 12px;
          font-size: 20px;
          color: rgba(72, 72, 72, 1);
          margin-bottom: 10px;
        }
        .btns {
          // margin-top: 10px;
        }
        .el-select {
          margin-right: 10px;
          margin-bottom: 10px;
        }
        .el-range-editor {
          margin-bottom: 10px;
        }
      }
      .el-table {
      }
    }
  }
}
.vip_Introduction {
  margin-top: 10px;
  ul {
    padding-left: 10px;
    li {
      list-style: none;
      span {
        font-size: 14px;
      }
    }
  }
}
</style>